<template>
  <el-row :gutter="10">
    <el-col :span="4" :xs="0">
      <span>&nbsp;</span>
    </el-col>

    <el-col :span="16" :xs="24">
      <el-menu
        :default-active="activeIndex"
        class="header-menu"
        mode="horizontal"
        @select="handleSelect"
        ref="getHeaderSize"
      >
        <el-menu-item index="main-content">
          <el-image
            :style="{
              width: headerChildHeight + 'px',
              height: headerChildHeight + 'px',
            }"
            :src="imgUrl"
          ></el-image>
        </el-menu-item>

        <!-- 一级导航 -->
        <template v-if="showNavigation">
          <template v-for="item in menuList">
            <el-submenu
              v-if="item.hasChildMenu == 1"
              :key="item.id"
              :index="item.menuLink"
            >
              <template slot="title">{{ item.menuNameCn }}</template>

              <!-- 二级导航 -->
              <template v-for="childOne in item.childList">
                <el-submenu
                  v-if="childOne.hasChildMenu == 1"
                  :key="childOne.id"
                  :index="childOne.menuLink"
                >
                  <template slot="title">{{ childOne.menuNameCn }}</template>

                  <!-- 三级导航 -->
                  <template v-for="childTwo in childOne.childList">
                    <el-submenu
                      v-if="childTwo.hasChildMenu == 1"
                      :key="childTwo.id"
                      :index="childTwo.menuLink"
                    >
                      <template slot="title">{{
                        childTwo.menuNameCn
                      }}</template>
                    </el-submenu>
                    <el-menu-item
                      v-else
                      :key="childTwo.id"
                      :index="childTwo.menuLink"
                      >{{ childTwo.menuNameCn }}</el-menu-item
                    >
                  </template>
                </el-submenu>
                <el-menu-item
                  v-else
                  :key="childOne.id"
                  :index="childOne.menuLink"
                  >{{ childOne.menuNameCn }}</el-menu-item
                >
              </template>
            </el-submenu>
            <el-menu-item v-else :key="item.id" :index="item.menuLink">{{
              item.menuNameCn
            }}</el-menu-item>
          </template>
        </template>

        <el-menu-item style="float: right" ref="getHeaderChildHeight">
          <el-popover
            class="searchInput"
            placement="bottom"
            width="400"
            trigger="click"
          >
            <el-input
              v-model="input"
              placeholder="请输入关键词..."
              @change="searchChange"
            >
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
            <el-button
              slot="reference"
              type="text"
              icon="el-icon-search"
              circle
              @click="searchChange"
            ></el-button>
          </el-popover>

          <el-button
            type="text"
            icon="el-icon-edit-outline"
            style="margin-right: 20px"
            circle
            @click="$router.push({ path: 'publish' })"
          ></el-button>

          <el-button-group v-if="!loginFlag">
            <el-button
              @click="(dialogFormVisible = true), (activeName = 'register')"
              >注册</el-button
            >
            <el-button
              @click="(dialogFormVisible = true), (activeName = 'login')"
              type="primary"
              >登录</el-button
            >
          </el-button-group>

          <!-- 用户头像区 -->
          <el-popover
            placement="bottom"
            width="150"
            trigger="click"
            v-model="userPopover"
          >
            <span style="text-align: center; display: block"
              >用户：{{ userInfo.username }}</span
            >
            <el-divider style="margin: 10px 0"></el-divider>
            <el-button
              @click="
                $router.push({
                  path: 'user-page',
                  query: { menuIndex: '1' },
                }),
                  (userPopover = !userPopover)
              "
              >我的主页</el-button
            >
            <el-button
              @click="
                $router.push({
                  path: 'user-page',
                  query: { menuIndex: '2' },
                }),
                  (userPopover = !userPopover)
              "
              >我的关注</el-button
            >
            <el-button
              @click="
                $router.push({
                  path: 'user-page',
                  query: { menuIndex: '3' },
                }),
                  (userPopover = !userPopover)
              "
              >编辑资料</el-button
            >
            <el-button @click="userPopover = !userPopover">退出登录</el-button>
            <el-button slot="reference" circle>
              <el-avatar
                v-if="loginFlag && userInfo.avatar != null"
                class="userAvatar"
                :src="userInfo.avatar"
              ></el-avatar>
              <el-avatar
                v-if="loginFlag && userInfo.avatar == null"
                class="userAvatar"
                icon="el-icon-user-solid"
              ></el-avatar>
            </el-button>
          </el-popover>
        </el-menu-item>
      </el-menu>

      <el-dialog
        :visible.sync="dialogFormVisible"
        width="22%"
        center
        :show-close="false"
      >
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          style="padding: 0 20px"
        >
          <!-- 登录页 -->
          <el-tab-pane label="登   录" name="login">
            <!-- 用户名/密码登录方式Form -->
            <el-form
              v-if="passwordLogin"
              :model="loginForm"
              label-position="left"
            >
              <el-form-item label="用户名" :label-width="formLabelWidth">
                <el-input
                  v-model="loginForm.username"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="密码" :label-width="formLabelWidth">
                <el-input
                  v-model="loginForm.password"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-form>

            <!-- 手机号/验证码登录方式Form -->
            <el-form v-if="codeLogin" :model="loginForm" label-position="left">
              <el-form-item label="手机号" :label-width="formLabelWidth">
                <el-input
                  v-model="loginForm.phone"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="验证码" :label-width="formLabelWidth">
                <el-input
                  v-model="loginForm.verificationCode"
                  autocomplete="off"
                >
                  <template slot="append" v-if="loginShowSmsButton">
                    <el-button @click="getLoginCode" type="primary" plain
                      >获取验证码</el-button
                    >
                  </template>
                  <template slot="append" v-if="!loginShowSmsButton">
                    <el-button type="primary" plain
                      >{{ loginSmsWaitTime }}s 后再次发送</el-button
                    >
                  </template>
                </el-input>
              </el-form-item>
            </el-form>

            <div>
              <el-link
                v-if="passwordLogin"
                type="danger"
                @click="
                  (codeLogin = true),
                    (passwordLogin = false),
                    (loginType = 'smscode')
                "
                >手机快捷登录</el-link
              >
              <el-link
                v-if="codeLogin"
                type="danger"
                @click="
                  (codeLogin = false),
                    (passwordLogin = true),
                    (loginType = 'password')
                "
                >密码登录</el-link
              >
              <el-link target="_blank" style="float: right">忘记密码？</el-link>
            </div>

            <div style="text-align: center; margin-top: 25px">
              <el-button style="width: 100%" type="primary" @click="loginButton"
                >登 录</el-button
              >
            </div>

            <div style="text-align: center; margin-top: 25px">
              <el-link :underline="false">还没有账号？</el-link>
              <el-link type="danger" @click="activeName = 'register'"
                >立即注册</el-link
              >
            </div>
          </el-tab-pane>

          <!-- 注册页 -->
          <el-tab-pane label="注   册" name="register">
            <!-- 注册Form -->
            <el-form :model="registerForm" label-position="left">
              <el-form-item label="手机号" :label-width="formLabelWidth">
                <el-input
                  v-model="registerForm.username"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="验证码" :label-width="formLabelWidth">
                <el-input
                  v-model="registerForm.verificationCode"
                  autocomplete="off"
                >
                  <template slot="append" v-if="registerShowSmsButton">
                    <el-button @click="getRegisterCode" type="primary" plain
                      >获取验证码</el-button
                    >
                  </template>
                  <template slot="append" v-if="!registerShowSmsButton">
                    <el-button type="primary" plain
                      >{{ registerSmsWaitTime }}s 后再次发送</el-button
                    >
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="密码" :label-width="formLabelWidth">
                <el-input
                  v-model="registerForm.password"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="确认密码" :label-width="formLabelWidth">
                <el-input
                  v-model="registerForm.checkPassword"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-form>

            <div style="margin-top: 25px">
              <el-link :underline="false">已有账号？</el-link>
              <el-link type="danger" @click="activeName = 'login'"
                >密码登录</el-link
              >
            </div>

            <div style="text-align: center; margin-top: 25px">
              <el-button style="width: 100%" type="primary"
                >立 即 注 册</el-button
              >
            </div>
          </el-tab-pane>
        </el-tabs>

        <div slot="footer" class="dialog-footer">
          <el-divider>第三方登录</el-divider>
          <el-button
            type="success"
            icon="el-icon-check"
            circle
            style="font-size: 40px; margin: 0"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-check"
            circle
            style="font-size: 40px; margin: 0 40px"
          ></el-button>
          <el-button
            type="primary"
            icon="el-icon-check"
            circle
            style="font-size: 40px; margin: 0"
          ></el-button>
        </div>
      </el-dialog>
    </el-col>

    <el-col :span="4" :xs="0">
      <span>&nbsp;</span>
    </el-col>
  </el-row>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      activeIndex: "main-content",
      imgUrl: "https://gulimall-yangrong.oss-cn-shanghai.aliyuncs.com/logo.png",
      direction: "ttb",
      modalFalse: false,
      headerChildHeight: "",
      headerHeight: "",
      headerWidth: document.body.clientWidth,
      marginLeftWidth: "",
      input: "",
      formLabelWidth: "70px",
      activeName: "login",
      dialogFormVisible: false,
      codeLogin: false,
      passwordLogin: true,
      // 登陆获取验证码按钮切换
      loginShowSmsButton: true,
      loginSmsWaitTime: 60,
      loginSmsWaitTimer: null,
      // 注册获取验证码按钮切换
      registerShowSmsButton: true,
      registerSmsWaitTime: 60,
      registerSmsWaitTimer: null,
      // 登陆方式
      loginType: "password",
      // 用户操作Popover弹窗
      userPopover: false,
      // 功能栏展开收缩
      showNavigation: true,
      loginForm: {
        username: "",
        password: "",
        phone: "",
        verificationCode: "",
      },
      registerForm: {
        username: "",
        password: "",
        verificationCode: "",
        checkPassword: "",
      },
      menuList: [],
      userInfo: {},
      loginFlag: false,
      timer: false,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    getHeaderWidth() {
      let _this = this;
      _this.$nextTick(() => {
        if (!_this.timer) {
          if (document.body.clientWidth < 1200) {
            _this.showNavigation = false;
          } else {
            _this.showNavigation = true;
          }
          _this.timer = true;
          setTimeout(function () {
            _this.timer = false;
          }, 200);
        }
      });
    },

    handleSelect(key, keyPath) {
      this.$router.push({
        path: key,
      });
    },

    handleClick(tab, event) {},

    loginButton() {
      this.$http({
        url: this.$http.adornUrl("/user/login"),
        method: "post",
        data: this.$http.adornData({
          username: this.loginForm.username,
          password: this.loginForm.password,
          phone: this.loginForm.phone,
          type: this.loginType,
          code: this.loginForm.verificationCode,
        }),
      }).then(({ data }) => {
        if (data.data.userInfo != null) {
          this.$message({
            message: "登录成功",
            type: "success",
          });
          this.userInfo = data.data.userInfo;
          this.loginFlag = true;
          this.dialogFormVisible = false;
          sessionStorage.setItem("user", JSON.stringify(this.userInfo));
        } else {
          this.$message.error(data.data.msg);
        }
      });
    },

    searchChange(value) {
      console.log(value);
    },

    getMenuList() {
      this.$http({
        url: this.$http.adornUrl("/public/tbhomepagemenu/getMenuList"),
        method: "get",
      }).then(({ data }) => {
        this.menuList = data.menuList;
      });
    },

    getLoginCode() {
      this.$http({
        url: this.$http.adornUrl("/user/sendSmsCode"),
        method: "get",
        params: this.$http.adornParams({
          phone: this.loginForm.phone,
          codeType: this.activeName,
        }),
      }).then(({ data }) => {
        if (data.code == 0) {
          this.$message({
            message: "验证码发送成功",
            type: "success",
          });

          const TIME_COUNT = 60;
          if (!this.loginSmsWaitTimer) {
            this.loginSmsWaitTime = TIME_COUNT;
            this.loginShowSmsButton = false;
            this.loginSmsWaitTimer = setInterval(() => {
              if (
                this.loginSmsWaitTime > 0 &&
                this.loginSmsWaitTime <= TIME_COUNT
              ) {
                this.loginSmsWaitTime--;
              } else {
                this.loginShowSmsButton = true;
                clearInterval(this.loginSmsWaitTimer);
                this.loginSmsWaitTimer = null;
              }
            }, 1000);
          }
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    getRegisterCode() {
      this.$http({
        url: this.$http.adornUrl("/user/sendSmsCode"),
        method: "get",
        params: this.$http.adornParams({
          phone: this.loginForm.phone,
          codeType: this.activeName,
        }),
      }).then(({ data }) => {
        if (data.code == 0) {
          this.$message({
            message: "验证码发送成功",
            type: "success",
          });

          const TIME_COUNT = 60;
          if (!this.registerSmsWaitTimer) {
            this.registerSmsWaitTime = TIME_COUNT;
            this.registerShowSmsButton = false;
            this.registerSmsWaitTimer = setInterval(() => {
              if (
                this.registerSmsWaitTime > 0 &&
                this.registerSmsWaitTime <= TIME_COUNT
              ) {
                this.registerSmsWaitTime--;
              } else {
                this.registerShowSmsButton = true;
                clearInterval(this.registerSmsWaitTimer);
                this.registerSmsWaitTimer = null;
              }
            }, 1000);
          }
        } else {
          this.$message.error(data.msg);
        }
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    let _this = this;
    // 判断用户数据是否存在
    var userJsonStr = sessionStorage.getItem("user");
    if (userJsonStr != null) {
      _this.userInfo = JSON.parse(userJsonStr);
      _this.loginFlag = true;
      _this.dialogFormVisible = false;
    }
    _this.headerChildHeight = _this.$refs.getHeaderChildHeight.$el.offsetHeight;
    _this.headerHeight = _this.$refs.getHeaderSize.$el.offsetHeight;
    // this.headerWidth = this.$refs.getHeaderSize.$el.offsetWidth;
    _this.marginLeftWidth = _this.$refs.getHeaderSize.$el.getBoundingClientRect().left;
    _this.getMenuList();
    window.onresize = () => {
      return (() => {
        _this.getHeaderWidth();
      })();
    };
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {
    // 注销window.onresize事件
    window.onresize = null;
  }, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
.el-menu--horizontal > .el-menu-item a,
.el-menu--horizontal > .el-menu-item a:hover {
  text-decoration: none;
}

.el-menu--horizontal > .el-menu-item.is-active {
  border-bottom: 0px white;
}

div /deep/ .el-submenu.is-active .el-submenu__title {
  border-bottom: 0px white;
}

.el-tab-pane {
  padding-top: 20px;
}

div /deep/ .el-dialog__header {
  padding: 0;
}

div /deep/ .el-dialog--center {
  border-radius: 6px;
}

.searchInput {
  vertical-align: unset;
}

.userAvatar >>> i {
  margin-right: 0;
  vertical-align: unset;
}

.el-popover .el-divider--horizontal {
  margin: 10px 0;
}

.el-popover .el-button {
  display: block;
  margin: 0 auto;
  width: -webkit-fill-available;
  border: none;
}
</style>

<style>
.el-button.is-circle {
  padding: 0;
}
</style>